package com.httpClient.cookies;

import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author bigFish
 * @Title: public:
 */
public class MyCookiesForGet {

    private String url =null;
    private String uri =null;
    private ResourceBundle bundle;
    CookieStore cookieStore = new BasicCookieStore();

    @BeforeTest
    public void beFor() {
        //读取配置文件
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        //根据key可以获取到value
        url = bundle.getString("test.url");
    }

    @Test
    public void testGetCookies() throws IOException {
        this.uri = bundle.getString("getCookies");
        //拼接地址
        HttpGet get = new HttpGet(url + uri);
        //构建client对象
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
        //执行请求并获取结果
        HttpEntity entity = client.execute(get).getEntity();
        //转换类型
        String s = EntityUtils.toString(entity, "utf-8");
        //输出信息
        System.out.println(s);
        //获取cookies信息
        List<Cookie> cookiesList = cookieStore.getCookies();
        for (Cookie cookie : cookiesList) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("[" + name + "," + value + "]");
        }
//        for (int i = 0; i < cookies.size(); i++) {
//            System.out.println(cookies.get(i));
//        }
    }

    @Test(dependsOnMethods = "testGetCookies")
    public void getByCookies() throws IOException {
        String uri = bundle.getString("getWithCookies");
        HttpGet get = new HttpGet(url + uri);
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
//        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(get);
        //获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String s = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(s);
        }
    }
}
